﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoundManager : ModuleBase<SoundManager>
{
    public AudioSource MusicPlayer;
    public AudioSource[] SoundPlayers;
    public const int SoundCount = 4;
    public SoundConfig mConfig;

    public override void Init()
    {
        GameObject go = new GameObject("SoundManager");
        MusicPlayer = go.AddComponent<AudioSource>();

        SoundPlayers = new AudioSource[SoundCount];
        for (int i = 0; i < SoundCount; i++)
        {
            SoundPlayers[i] = go.AddComponent<AudioSource>();
        }

        LoadManager.Instance.LoadAsset("sound", "SoundConfig", "prefab", typeof(GameObject), data =>
        {
            mConfig = (data as GameObject).GetComponent<SoundConfig>();
        }
        , false);

        PlayMusic();
    }

    public override void Update(float dt)
    {

    }

    public void PlayMusic()
    {
        LoadManager.Instance.LoadAsset("sound", "Musci", "mp3", typeof(AudioClip), data =>
        {
            MusicPlayer.clip = data as AudioClip;
            MusicPlayer.loop = true;
            MusicPlayer.volume = 0.2f;
            MusicPlayer.Play();
        }
        , false);
    }

    public void PlayOneSheet(string sound)
    {
        AudioSource player = GetFreePlayer();
        if (player != null)
        {
            AudioClip clip = mConfig.GetAudioClip(sound);
            player.PlayOneShot(clip);
        }
    }

    public AudioSource GetFreePlayer()
    {
        for (int i = 0; i < SoundCount; i++)
        {
            if (!SoundPlayers[i].isPlaying)
                return SoundPlayers[i];
        }
        return null;
    }
}

public static class SoundDefine
{
    public static string Attack = "Attack";
    public static string Attack2 = "Attack2";
    public static string HardFall = "HardFall";
    public static string FootStep = "FootStep";
    public static string Jump = "Jump";
}